package logic

import (
	"errors"
	"sems/dao"
	"sems/model"

	"go.uber.org/zap"
)

func GetEquipments(categoryName, equipmentName string, currentPage int) (equipments []model.Equipment, list *model.PaginationList, err error) {
	if currentPage <= 0 {
		currentPage = 1
	}
	offset := (currentPage - 1) * Size
	var count int64
	equipments, count, err = dao.GetEquipments(categoryName, equipmentName, Size, offset)
	if err != nil {
		zap.L().Error("查询器材列表出错了", zap.Error(err))
		err = errors.New("查询器材列表出错了")
		return
	}
	for i, equipment := range equipments {
		equipments[i].CategoryName = dao.GetEquipmentCategoryNameById(equipment.CategoryID)
	}
	totalPages := GetTotalPages(count)
	if currentPage > int(totalPages) {
		currentPage = int(totalPages)
	}
	list = &model.PaginationList{
		Count:       count,
		TotalPages:  totalPages,
		CurrentPage: currentPage,
		Size:        Size,
	}
	return equipments, list, nil
}

func GetEquipmentInfo(equipmentId int) (equipment model.Equipment, err error) {
	equipment, err = dao.GetEquipmentInfo(equipmentId)
	if err != nil {
		zap.L().Error("查询器材详情出错了", zap.Error(err))
		err = errors.New("查询器材详情出错了")
		return model.Equipment{}, err
	}
	equipment.CategoryName = dao.GetEquipmentCategoryNameById(equipment.CategoryID)
	return equipment, nil
}

func GetBorrowRecord(userId int32, equipmentName string, currentPage int) (borrowRecords []model.BorrowRecord, list *model.PaginationList, err error) {
	if currentPage <= 0 {
		currentPage = 1
	}
	offset := (currentPage - 1) * Size
	var count int64
	borrowRecords, count, err = dao.GetBorrowRecord(userId, equipmentName, Size, offset)
	if err != nil {
		zap.L().Error("查询借阅记录列表出错了", zap.Error(err))
		err = errors.New("查询器材列表出错了")
		return
	}
	for i, record := range borrowRecords {
		userInfo, _ := dao.GetUserInfo(int(record.UserID))
		borrowRecords[i].Username = userInfo.Username
	}
	totalPages := GetTotalPages(count)
	if currentPage > int(totalPages) {
		currentPage = int(totalPages)
	}
	list = &model.PaginationList{
		Count:       count,
		TotalPages:  totalPages,
		CurrentPage: currentPage,
		Size:        Size,
	}
	return borrowRecords, list, nil
}

func GetAllBorrowRecord(equipmentName string, currentPage int) (borrowRecords []model.BorrowRecord, list *model.PaginationList, err error) {
	if currentPage <= 0 {
		currentPage = 1
	}
	offset := (currentPage - 1) * Size
	var count int64
	borrowRecords, count, err = dao.GetAllBorrowRecord(equipmentName, Size, offset)
	if err != nil {
		zap.L().Error("查询借阅记录列表出错了", zap.Error(err))
		err = errors.New("查询器材列表出错了")
		return
	}
	for i, record := range borrowRecords {
		userInfo, _ := dao.GetUserInfo(int(record.UserID))
		borrowRecords[i].Username = userInfo.Username
	}
	totalPages := GetTotalPages(count)
	if currentPage > int(totalPages) {
		currentPage = int(totalPages)
	}
	list = &model.PaginationList{
		Count:       count,
		TotalPages:  totalPages,
		CurrentPage: currentPage,
		Size:        Size,
	}
	return borrowRecords, list, nil
}
